﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Soul.XLS.Test
{
    public class JavaScriptColumn
    {
        public string Code { get; set; }

        public string Width { get; set; }

        public string Title { get; set; }

        public ICollection<JavaScriptColumn> Children { get; set; } = new List<JavaScriptColumn>();

        public static ExcelTable CreateTable(string json)
        {
            var jsavaScriptColumnRoot = new JavaScriptColumn()
            {
                Children =JsonSerializer.Deserialize<List<JavaScriptColumn>>(json, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString
                })
            };
            var excelColumnRoot = Map(jsavaScriptColumnRoot);
            var columns = new ExcelColumnCollection();
            columns.AddRange(excelColumnRoot.Items);
            var table = new ExcelTable();
            table.ApplyHeaders(columns);
            return table;
        }

        private static ExcelColumn Map(JavaScriptColumn rootColumn)
        {
            if (rootColumn == null)
                return null;

            var excelColumn = new ExcelColumn(rootColumn.Title, style => 
            {
                style.ColumnWidth = Convert.ToInt32(rootColumn.Width);
            });

            foreach (var item in rootColumn.Children)
            {
                var column = Map(item);
                if (column != null)
                {
                    excelColumn.Items.Add(column);
                }
            }
            return excelColumn;
        }
    }
}
